<template>
  <el-dialog
    :title="{ add: '新增文章', edit: '修改文章' }[mode]"
    :visible.sync="dialogVisible"
    width="50%"
    background-color="#409eff"
    @close="closeEvent"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <!-- 富文本编辑器 -->

      <!-- star -->
      <el-form-item label="文章内容:" style="height: 80%" prop="articleBody">
        <!-- 富文本编辑器 -->
        <quill-editor
          id="edit2"
          placeholder=""
          ref="myQuillEditor"
          v-model="form.articleBody"
          :options="editorOption"
        />
        <el-upload
          accept="image/*"
          id="imageupload"
          action="#"
          v-show="false"
          :before-upload="beforeUpload"
          :http-request="
            res => {
              return httpRequest(res)
            }
          "
        ></el-upload>
      </el-form-item>
      <!-- end -->
      <el-form-item label="视频地址" prop="videoURL">
        <el-input v-model="form.videoURL" placeholder="请输入视频地址">
        </el-input>
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <template>
        <el-button @click="closeEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 上传图片
import COS from 'cos-js-sdk-v5'
import { quillEditor } from 'vue-quill-editor'
import { add, update } from '@/api/hmmm/articles.js'
var cos = new COS({
  SecretId: 'AKIDXu0pOghSyEDvMbZHrHSN2SdYFhwve7LK',
  SecretKey: 'mDWbQzIL7evwhCQDn7E7mBKCpCMI0SeZ'
})
export default {
  components: { quillEditor },
  data () {
    return {
      dialogVisible: false,
      form: {
        id: null,
        title: '',
        articleBody: '',
        videoURL: ''
      },
      mode: 'add',
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'change' }
        ],
        articleBody: [
          { required: true, message: '请输入文章标题', trigger: 'change' }
        ]
      },
      // 富文本编辑器配置项

      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              ['blockquote', 'code-block'], // 引用代码块
              ['image', 'link'] // 链接、图片、视频
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  document
                    .querySelector('#imageupload .el-upload__input')
                    .click()
                }
              }
            }
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        } // 工具菜单栏配置
      }
    }
  },

  methods: {
    show (row) {
      this.form.id = row.id
      this.form.title = row.title
      this.form.articleBody = row.articleBody
      this.form.videoURL = row.videoURL
    },
    async submit () {
      if (this.mode === 'add') {
        await add(this.form)
        // console.log(res, 1111)
      }
      if (this.mode === 'edit') {
        await update(this.form)
      }
      this.closeEvent()
      this.$emit('getlist')
      this.$message.success('新增成功')
    },
    closeEvent () {
      this.form.id = ''
      this.form.title = ''
      this.form.articleBody = ''
      this.form.videoURL = ''
      this.dialogVisible = false
      this.$refs.form.resetFields()
      this.datalist = {}
      // console.log(111)
    },
    // 富文本编辑器相关
    beforeUpload (file) {
      // console.log(file)
      // 上传前，限制 文件大小与类型
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/gif'
      const limit2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只支持png、jpg、gif格式的图片')
      }
      if (!limit2M) {
        this.$message.error('请上传2MB内的图片')
      }
      return isImage && limit2M
    },
    httpRequest (res) {
      cos.putObject(
        {
          Bucket: 'gogomusic-1251140474' /* 存储桶: */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须是字符串 */,
          StorageClass: 'STANDARD', // 固定值
          Body: res.file // 上传文件对象
        },
        (err, data) => {
          if (data) {
            var quill = this.$refs.myQuillEditor.quill
            // 获取光标位置
            const pos = quill.getSelection().index
            // 插入图片到光标位置
            quill.insertEmbed(pos, 'image', 'http://' + data.Location)
          } else {
            this.$message.error(`图片插入失败${err}`)
          }
          // this.imageUrl = 'http://' + data.Location
          // this.$emit('input', 'http://' + data.Location)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped></style>
